﻿using Batman.Core;
using Batman.Core.Databases;
using Batman.Core.Utilities;
using Batman.SQLScripts;
using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;

namespace Batman.Web.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CommonController : ControllerBase
    {
        IConfiguration Configuration;

        static string _connectionString;

        public CommonController(IConfiguration configuration)
        {
            Configuration = configuration;

            if (_connectionString == null)
                _connectionString = Configuration["connectionStrings:default"];
        }

        public string Get()
        {
            var dict = Request.QueryString.ToDictionary();

            var commandTexts = CommonDataSelect.GetCommands(dict);

            var results = new List<object>();

            using (var conn = ConnectionFactory.GetConnection(_connectionString))
            {
                var commandText = string.Join(";", commandTexts);

                using (var multi = conn.QueryMultiple(commandText, dict))
                {
                    for (var index = 0; index < commandTexts.Count; index++)
                    {
                        results.Add(multi.Read().ToList());
                    }
                }
            }


            return JsonUtil.Serialize(results);
        }
    }
}
